package com.czy.owner.ui.accountbalance;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.czy.otherlib.swipetoloadlayout.OnLoadMoreListener;
import com.czy.otherlib.swipetoloadlayout.OnRefreshListener;
import com.czy.otherlib.swipetoloadlayout.SwipeToLoadLayout;
import com.czy.owner.R;
import com.czy.owner.adapter.TransactionRecordAdapter;
import com.czy.owner.api.TransactionRecordApi;
import com.czy.owner.callback.RecyclerHeadersDecoration;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.AccountHistoryModel;
import com.czy.owner.entity.RechargeEntity;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.utils.SharedPreferencesUtils;
import com.czy.owner.utils.TimeUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;


/**
 * Created by wanyyang on 2017/1/10 0010.
 * 交易记录
 */
public class TransactionRecordActivity extends BaseActivity implements OnRefreshListener, OnLoadMoreListener {
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.refresh_target)
    RecyclerView rvPunchRecord;
    @BindView(R.id.swipeToLoadLayout)
    SwipeToLoadLayout swipeToLoadLayout;
    RecyclerHeadersDecoration headersDecor = null;

    private TransactionRecordAdapter mAdapter;
    private int page = 1;

    private List<AccountHistoryModel.ListBean> myList = new ArrayList<>();
    private TreeMap<String, Integer> groupBillsMap = new TreeMap<>();
    private int storeId;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_transaction_record;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(R.string.transaction_record);
        storeId = getIntent().getIntExtra("storeId",0);
        mAdapter = new TransactionRecordAdapter(TransactionRecordActivity.this, myList);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(TransactionRecordActivity.this);
        rvPunchRecord.setLayoutManager(layoutManager);
        rvPunchRecord.setAdapter(mAdapter);
        if (headersDecor != null) {
            rvPunchRecord.removeItemDecoration(headersDecor);
        }
        headersDecor = new RecyclerHeadersDecoration(mAdapter);
        rvPunchRecord.addItemDecoration(headersDecor);
        swipeToLoadLayout.setRefreshing(true);
        swipeToLoadLayout.setOnRefreshListener(this);
        swipeToLoadLayout.setOnLoadMoreListener(this);
    }

    @Override
    protected void updateViews() {

    }

    private void getDataList(final boolean isFirst) {
        if (isFirst) {
            myList.clear();
            groupBillsMap.clear();
        }

        RequestParams params = new RequestParams(Constants.APP_API_BASE + Constants.OWN_ACCOUNTHISTORY);
        params.addBodyParameter("session",UserHelper.getInstance().getSessionInfoModel(this).getSession());
        params.addBodyParameter("storeId",storeId+"");
        params.addBodyParameter("page",page+"");
        params.addBodyParameter("size","1000");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyLog.e("yang","onSuccess=="+result);
                String data = PhoneUtils.checkResponseFlag(TransactionRecordActivity.this,result);
                if(data!=null){
                    Gson gson = new GsonBuilder().create();
                    AccountHistoryModel  model = gson.fromJson(data, AccountHistoryModel.class);
                    setDataList(model.getList());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                MyLog.e("yang","onError=="+ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    private void setDataList(List<AccountHistoryModel.ListBean> list) {
        try {
            for (int i = 0; i < list.size(); i++) {
                String groupName = TimeUtils.formatTimeDifference5(list.get(i).getEventTime());
                MyLog.i("yang", "groupName==" + groupName);
                //如果Map已经存在以该记录的日期为分组名的分组，则将该条记录插入到该分组中
                if (groupBillsMap.containsKey(groupName)) {
                    list.get(i).setSort(groupBillsMap.get(groupName));
                    //如果不存在，以该记录的日期作为分组名称创建分组，并将该记录插入到创建的分组中
                } else {
                    groupBillsMap.put(groupName, i);
                    list.get(i).setSort(Long.valueOf(i));
                    list.get(i).setMyGroupName(groupName);
                }
            }
            if (page == 1) {
                myList = list;
            } else {
                myList.addAll(list);
            }
            mAdapter.setList(myList);
            checkTips(myList);
            swipeToLoadLayout.setRefreshing(false);
            swipeToLoadLayout.setLoadingMore(false);

        } catch (Exception e) {

        }


    }

    private void checkTips(List<AccountHistoryModel.ListBean> myList) {
        if (myList != null && myList.size() > 0) {
            tvTip.setVisibility(View.GONE);
        } else {
            tvTip.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onLoadMore() {
        page++;
        getDataList(false);
    }

    @Override
    public void onRefresh() {
        swipeToLoadLayout.setLoadMoreEnabled(true);
        page = 1;
        getDataList(true);
    }


}
